<?php

namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\MenuService;
use support\Service\UserRoleService;
use support\Service\UserService;

class UserLogic extends BackendLogic
{

    private  $menuService;
    private  $userRoleService;

    public function __construct()
    {
        $this->service = Container::get(UserService::class);
        $this->menuService = Container::get(MenuService::class);
        $this->userRoleService = Container::get(UserRoleService::class);
    }

    /**
     * 获取用户列表
     * @return array
     */
    public  function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (!empty($param['username'])) $where[] = ["username", 'like', "%{$param['username']}%"];
        $list =$this->service->getListPage($where, ['*'], ['id' => 'desc']);
        if ($list['total'] <= 0) return message($list);
        foreach ($list['list'] as $k => $v) {
            $roles = $this->userRoleService->getUserRoleList($v['id']) ?? [];
            $list['list'][$k]['roles'] = array_map(function ($v) {
                return $v['name'];
            }, $roles);
            $list['list'][$k]['avatar']=siteUrl($v['avatar']);
        }
        return message($list);
    }

    /**
     * 获取用户详情
     * @return array
     */
    public  function info(): array
    {
        $info = parent::info(); // TODO: Change the autogenerated stub
        if (!$info['data']) return $info;
        $info['data']['roles'] = $this->userRoleService->getUserRoleList($info['data']['id']);;
        return $info;
    }

    /**
     * 获取后台用户信息
     * @param int $userId 用戶ID
     * @return array
     */
    public  function getUserInfo(int $userId): array
    {
        //获取用户信息
        $user_info = $this->service->getUserInfo($userId);
        $user_info['avatar']=siteUrl($user_info['avatar']);
        // 权限节点列表
        if (!isset($user_info['permission'])) {
            $permissionList =$this->menuService->getPermissionsList($userId);
            $user_info['permission'] = $permissionList;
        }
        $user_info['role'] = 'admin';
        return message($user_info);
    }

    /**
     * 编辑用户信息
     * @param $userId
     * @return array
     */
    public  function edit()
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['realname'])) throw new ApiException('请输入用户姓名');
        if (empty($data['nickname'])) throw new ApiException('请输入用户昵称');
        if (empty($data['email'])) throw new ApiException('请输入用户邮箱');
        if (empty($data['mobile'])) throw new ApiException('请输入手机号');
        if (empty($data['username'])) throw new ApiException('请输入登录账号');
        if (!$id && (empty($data['password']))) throw new ApiException('请输入登录密码');
        $save['username'] = trim($data['username']);
        $save['password'] = trim($data['password']);
        $save['email'] = $data['email'];
        $save['realname'] = $data['realname'];
        $save['nickname'] = $data['nickname'];
        $save['mobile'] = $data['mobile'];
        $save['gender'] = $data['gender'] ?? 1;
        $save['status'] = $data['status'] ?? 1;
        $save['avatar'] = $data['avatar'] ?? '';
        $save['note'] = $data['note'] ?? '';
        if (!$id) {
            $save['salt'] = uniqid();
            $save['password'] = get_password($save['password'] . $save['salt']);
            // 用户名重复性验证
            $count = $this->service->getUserCountByWhere([["username", '=', $save['username']], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的用户名');
            $mobile_count = $this->service->getUserCountByWhere([["mobile", '=', $save['mobile']], ["mark", "=", 1]]);
        } else {
            if (!$save['password']) {
                unset($save['password']);
            } else {
                $save['password'] = get_password($save['password'] . $save['username']);
            }
            // 用户名重复性验证
            $count = $this->service->getUserCountByWhere([["username", '=', $save['username']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的用户名');
            $mobile_count = $this->service->getUserCountByWhere([["mobile", '=', $save['mobile']], ["id", "<>", $id], ["mark", "=", 1]]);
        }
        if ($mobile_count > 0) {
            throw new ApiException('系统中已存在相同的手机号');
        }
        if ($id == 0) {
            $this->service->add($save);
        } else {
            unset($save['username']);
            $this->service->save($save, $id);
        }
        return message();
    }

    /**
     * 修改指定用户密码
     * @param
     * @return
     */
    public  function restartPwd(): array
    {
        // 获取参数
        $data = request()->post();
        // 新密码
        $newPassword = trim($data['password'] ?? '');
        if (!$newPassword) throw new ApiException('新密码不能为空');
        $userId = $data['id'] ?? 0;
        if (!$userId) throw new ApiException('用户信息不存在');
        $userInfo = $this->service->getInfo($userId);
        if (!$userInfo) throw new ApiException('用户信息不存在');
        $salt = uniqid();
        $item = [
            'password' => get_password($newPassword . $salt),
            'salt' => $salt
        ];
        $result = $this->service->save($item, $userId);
        if ($result === false) throw new ApiException('修改失败');
        return message();
    }

    /**
     * 修改密码
     * @param int $userId 用户ID
     * @return mixed
     */
    public  function updatePwd(int $userId)
    {
        // 获取参数
        $param = request()->all();
        // 原始密码
        $oldPassword = trim($param['oldPassword']);
        if (!$oldPassword) throw new ApiException('旧密码不能为空');
        // 新密码
        $newPassword = trim($param['newPassword']);
        if (!$newPassword) throw new ApiException('新密码不能为空');
        $userInfo = $this->service->getInfo($userId);
        if (!$userInfo) throw new ApiException('用户信息不存在');
        if ($userInfo['password'] != get_password($oldPassword . $userInfo['salt'])) throw new ApiException('旧密码输入不正确');
        $item = [
            'password' => get_password($newPassword . $userInfo['salt']),
        ];
        $result =  $this->service->save($item, $userId);
        if ($result === false) throw new ApiException('修改失败');
        return message();
    }


    /**
     * 更改用户信息
     * @param int $user_id 用户ID
     * @return array
     */
    public  function updateUserInfo(int $user_id): array
    {
        $data = request()->post();
        $save['intro'] = trim($data['intro'] ?? '');
        $save['avatar'] = $data['avatar'] ?? '';
        $save['email'] = $data['email'] ?? '';
        $save['gender'] = $data['gender'] ?? 3;
        $save['mobile'] = $data['mobile'] ?? '';
        $save['nickname'] = $data['nickname'] ?? '';
        $save['realname'] = $data['realname'] ?? '';
        $this->service->save($save, $user_id);
        return message();
    }

    /**
     * 查询用户角色
     * @return array
     */
    public  function getRoles()
    {
        $userId = request()->get('userId');
        if (!$userId) throw new ApiException('用户不存在');
        $roles = $this->userRoleService->getUserRoleList($userId) ?? [];
        $roles = array_map(function ($v) {
            return $v['id'];
        }, $roles);
        return message($roles);
    }

    /**
     * 编辑用户角色
     * @return array
     */
    public  function updateRoles(): array
    {
        $data = request()->post();
        if (empty($data['id'])) throw new ApiException('用户不存在');
        if (empty($data['roles'])) throw new ApiException('请选择用户角色');
        // 删除已存在的用户角色关系数据
        $this->userRoleService->deleteUserRole($data['id']);
        $this->userRoleService->insertUserRole($data['id'], $data['roles']);
        return message();
    }


}
